#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 705;

mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int n, m;
int a[N][N];
bool check(int x, int y) {
  return a[x][y] == a[x - 1][y] || a[x][y] == a[x + 1][y] ||
         a[x][y] == a[x][y - 1] || a[x][y] == a[x][y + 1];
}
void solve() {
  cin >> n >> m;
  rep(i, 1, n) rep(j, 1, m) cin >> a[i][j];
  rep(j, 1, m) a[n + 1][j] = 0;
  rep(i, 1, n) a[i][m + 1] = 0;
  set<int> st1, st2;
  rep(i, 1, n) rep(j, 1, m) {
    st1.insert(a[i][j]);
    if (check(i, j)) st2.insert(a[i][j]);
  }
  int tot = st1.size() + st2.size();
  if (st2.size())
    tot -= 2;
  else
    tot -= 1;
  cout << tot << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}